package com.jhgsys.internal.incentive.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.incentive.dto.IncentiveQuotaConfigDto;
import com.jhgsys.internal.incentive.entity.IncentiveQuotaConfig;
import com.jhgsys.internal.incentive.entity.IncentiveQuotaGoods;
import com.jhgsys.internal.incentive.entity.IncentiveRewardMatters;
import com.jhgsys.internal.incentive.service.IIncentiveQuotaConfigService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import java.util.Date;

/**
 * 开单人额度设置 Controller
 *
 * @author zhangwei
 * @date 2024-08-30 09:28:03
 */
@Slf4j
@Validated
@Controller
public class IncentiveQuotaConfigController extends BaseController {

    @Autowired
    private IIncentiveQuotaConfigService incentiveQuotaConfigService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "incentiveQuotaConfig")
    @RequiresPermissions("incentiveQuotaConfig:view")
    public String incentiveQuotaConfigIndex(Model model){
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("userId",getCurrentUser().getUserId());
        return FebsUtil.view("incentive/incentiveQuotaConfig/incentiveQuotaConfigList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "incentiveQuotaConfig/add")
    @RequiresPermissions("incentiveQuotaConfig:add")
    public String incentiveQuotaConfigAdd(){
        return FebsUtil.view("incentive/incentiveQuotaConfig/incentiveQuotaConfigEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "incentiveQuotaConfig/update/{id}")
    @RequiresPermissions("incentiveQuotaConfig:edit")
    public String incentiveQuotaConfigUpdate(Model model, @PathVariable("id") String id){
        model.addAttribute("incentiveQuotaConfig", incentiveQuotaConfigService.findIncentiveQuotaConfigById(id));
        return FebsUtil.view("incentive/incentiveQuotaConfig/incentiveQuotaConfigEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "incentiveQuotaConfig/apply/{userId}")
    @RequiresPermissions("incentiveQuotaConfig:apply")
    public String incentiveQuotaConfigApply(Model model, @PathVariable("userId") String userId){
        model.addAttribute("incentiveQuotaConfig", incentiveQuotaConfigService.findIncentiveQuotaConfigByUserId(userId));
        return FebsUtil.view("incentive/incentiveQuotaConfig/incentiveQuotaConfigApply");
    }

    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @GetMapping("incentiveQuotaConfig")
    @ResponseBody
    @RequiresPermissions("incentiveQuotaConfig:view")
    public FebsResponse getAllIncentiveQuotaConfigs(IncentiveQuotaConfig incentiveQuotaConfig) {
        return new FebsResponse().success().data(incentiveQuotaConfigService.findIncentiveQuotaConfigList(incentiveQuotaConfig));
    }

    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @GetMapping("incentiveQuotaConfig/list")
    @ResponseBody
    @RequiresPermissions("incentiveQuotaConfig:view")
    public FebsResponse incentiveQuotaConfigList(QueryRequest request, IncentiveQuotaConfig incentiveQuotaConfig) {
        Map<String, Object> dataTable = getDataTable(this.incentiveQuotaConfigService.findIncentiveQuotaConfigPage(request, incentiveQuotaConfig));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 IncentiveQuotaConfig
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @Log("新增IncentiveQuotaConfig")
    @PostMapping("incentiveQuotaConfig")
    @ResponseBody
    @RequiresPermissions("incentiveQuotaConfig:add")
    public FebsResponse addIncentiveQuotaConfig(@RequestBody IncentiveQuotaConfigDto incentiveQuotaConfigDto) {
        try {
            //必填校验
            this.checkNecessaryColumns(incentiveQuotaConfigDto,false);
            IncentiveQuotaConfig query = new IncentiveQuotaConfig();
            query.setYear(incentiveQuotaConfigDto.getYear());
            query.setUserId(incentiveQuotaConfigDto.getUserId());
            query.setStatus("1");
            if(null != incentiveQuotaConfigService.findIncentiveQuotaConfig(query)){
                return failure("当前开单人该年度额度已设置");
            }
            incentiveQuotaConfigDto.setCreatedBy(getCurrentUser().getUserName());
            this.incentiveQuotaConfigService.createIncentiveQuotaConfig(incentiveQuotaConfigDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增IncentiveQuotaConfig失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 逻辑删除 IncentiveQuotaConfig
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @Log("逻辑删除IncentiveQuotaConfig")
    @GetMapping("incentiveQuotaConfig/delete/{id}")
    @ResponseBody
    @RequiresPermissions("incentiveQuotaConfig:delete")
    public FebsResponse deleteIncentiveQuotaConfig(@PathVariable("id") String incentiveQuotaConfigIds) {
        try {
            IncentiveQuotaConfig incentiveQuotaConfig = new IncentiveQuotaConfig();
            incentiveQuotaConfig.setDeletedBy(getCurrentUser().getUserName());
            incentiveQuotaConfig.setDeletedTime(new Date());
            incentiveQuotaConfig.setDeletedFlg(FebsConstant.INVALID);
            this.incentiveQuotaConfigService.deleteIncentiveQuotaConfig(incentiveQuotaConfig,incentiveQuotaConfigIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除IncentiveQuotaConfig失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
    * 物理删除 IncentiveQuotaConfig
    * @author zhangwei
    * @date 2024-08-30 09:28:03
    */
    @Log("物理删除IncentiveQuotaConfig")
    @GetMapping("incentiveQuotaConfig/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("incentiveQuotaConfig:delete")
    public FebsResponse physicallyDeleteIncentiveQuotaConfig(@PathVariable("id") String incentiveQuotaConfigIds) {
        try {
            this.incentiveQuotaConfigService.physicallyDeleteIncentiveQuotaConfig(incentiveQuotaConfigIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除IncentiveQuotaConfig失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 修改 IncentiveQuotaConfig
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @Log("修改IncentiveQuotaConfig")
    @PostMapping("incentiveQuotaConfig/update")
    @ResponseBody
    @RequiresPermissions("incentiveQuotaConfig:edit")
    public FebsResponse updateIncentiveQuotaConfig(@RequestBody IncentiveQuotaConfigDto incentiveQuotaConfigDto) {
        try {
            //必填校验
            this.checkNecessaryColumns(incentiveQuotaConfigDto,true);
            incentiveQuotaConfigDto.setUpdatedBy(getCurrentUser().getUserName());
            this.incentiveQuotaConfigService.updateIncentiveQuotaConfig(incentiveQuotaConfigDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改IncentiveQuotaConfig失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 修改事项启用状态
     * @param incentiveQuotaConfig
     * @return
     * @throws FebsException
     */
    @Log("修改状态")
    @PostMapping("incentiveQuotaConfig/updateStatus")
    @ResponseBody
    @RequiresPermissions(value={"incentiveQuotaConfig:edit"},logical= Logical.OR)
    public FebsResponse updateStatus(IncentiveQuotaConfig incentiveQuotaConfig) {
        try {
            if(incentiveQuotaConfig.getStatus().equals("1")){
                IncentiveQuotaConfig query = new IncentiveQuotaConfig();
                query.setYear(incentiveQuotaConfig.getYear());
                query.setUserId(incentiveQuotaConfig.getUserId());
                query.setStatus("1");
                if(null != incentiveQuotaConfigService.findIncentiveQuotaConfig(query)){
                    return failure("当前开单人该年度额度已设置");
                }
            }
            incentiveQuotaConfig.setUpdatedBy(getCurrentUser().getUserName());
            incentiveQuotaConfig.setUpdatedTime(new Date());
            this.incentiveQuotaConfigService.updateById(incentiveQuotaConfig);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改状态失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @GetMapping("incentiveQuotaConfigsSelectOne")
    @ResponseBody
    @RequiresPermissions("incentiveQuotaConfig:view")
    public FebsResponse incentiveQuotaConfigsSelectOne(IncentiveQuotaConfig incentiveQuotaConfig) {
        incentiveQuotaConfig.setUserId(getCurrentUserId());
        List<IncentiveQuotaConfig> incentiveQuotaConfigList= incentiveQuotaConfigService.findIncentiveQuotaConfigList(incentiveQuotaConfig);
        if(!CollectionUtils.isEmpty(incentiveQuotaConfigList)){
            return new FebsResponse().success().data(incentiveQuotaConfigList.get(0));
        }else {
            return new FebsResponse().success().data(null);
        }

    }


    /**
     * 新增保存时，字段必填项校验
     * @author zhangwei
     * @date 2024-08-30 14:19:50
     */
    private FebsResponse checkNecessaryColumns(IncentiveQuotaConfig incentiveQuotaConfig,boolean editFlg)  {
        if(editFlg && StringUtils.isBlank(incentiveQuotaConfig.getQuotaConfigId())){
            return failure("主键不能为空");
        } else if(StringUtils.isBlank(incentiveQuotaConfig.getRealName())){
            return failure("姓名不能为空");
        } else if(null == incentiveQuotaConfig.getYear()){
            return failure("年份不能为空");
        } else if(null == incentiveQuotaConfig.getPenaltyBonusRatio()){
            return failure("罚款奖金比例不能为空");
        } else if(null == incentiveQuotaConfig.getTotalQuota()){
            return failure("总额度不能为空");
        }else{
            return success();
        }
    }
}
